package com.geek.factory.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geek.factory.constant.RedisImgConstant;
import com.geek.factory.constant.SuccessConstant;
import com.geek.factory.entity.TContract;
import com.geek.factory.request.ContractWithUsersRequest;
import com.geek.factory.result.Result;
import com.geek.factory.service.TContractService;
import com.geek.factory.vo.TContractQueryVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import org.springframework.util.ResourceUtils;
import java.io.*;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import static com.geek.factory.constant.SuccessConstant.FAIL;
import static com.geek.factory.constant.SuccessConstant.SUCCESS;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2025-06-21
 */
@RestController
@RequestMapping("/t_contract")
@Api(tags = "后台系统的 - 合同管理模块")
@Slf4j
public class TContractController {

    @Autowired
    private TContractService tContractService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @ApiOperation("获取所有合同信息")
    @GetMapping("{list}")
    public Result findAllContract() {
        List<TContract> list = tContractService.list();
        if(!CollectionUtils.isEmpty(list)){
            return new Result(SUCCESS, "查询成功", list);
        }
        return new Result(FAIL, "查询失败");
    }

    @ApiOperation("通过ID查询合同信息")
    @GetMapping("{id}")
    public Result findContractById(@ApiParam("合同ID") @PathVariable("id") Integer id) {
        TContract contract = tContractService.getById(id);
        log.info("contract: {}", contract);
        if(contract != null){
            return new Result(SUCCESS, "查询成功", contract);
        }
        return new Result(FAIL, "查询失败");
    }
    @ApiOperation("新增合同")
    @PostMapping("add")
    public Result addContract(    @RequestParam(value = "userIds", required = false) Integer[] userIds
            , @ApiParam("合同信息") @RequestBody TContract contract) {
        log.info("接收到的合同数据: {}", contract.toString());

        // 验证必填字段
        if (StringUtils.isEmpty(contract.getName()) || StringUtils.isEmpty(contract.getType())) {
            log.error("缺少必填字段");
            return new Result(FAIL, "缺少必填字段");
        }

        // 设置默认值
        if (contract.getStatus() == null) {
            contract.setStatus(0); // 默认草稿状态
        }
        if (contract.getCreateTime() == null) {
            contract.setCreateTime(LocalDateTime.now());
        }
        contract.setUpdateTime(LocalDateTime.now());

        boolean save = tContractService.save(userIds, contract);
        log.info("保存结果: {}", save);

        if(save){
            //新增套餐时，实际插入到数据库中的图片信息   DB
            redisTemplate.opsForSet().add(RedisImgConstant.UPLOAD_DB_PIC , contract.getContractFile());
            return new Result(SUCCESS, "新增成功");
        }
        return new Result(FAIL, "新增失败");
    }

    @ApiOperation("删除合同")
    @DeleteMapping("{id}")
    public Result deleteContract(@ApiParam("合同ID") @PathVariable("id") Integer id) {
        boolean delete = tContractService.removeById(id);
        log.info("delete: {}", delete);
        if(delete){
            return new Result(SUCCESS, "删除成功");
        }
        return new Result(FAIL, "删除失败");
    }

    @ApiOperation("修改合同")
    @PutMapping
    public Result updateContract(@ApiParam("合同信息") @RequestBody TContract contract) {
        // 设置更新时间
        contract.setUpdateTime(LocalDateTime.now());
        
        boolean update = tContractService.updateById(contract);
        log.info("update: {}", update);
        if(update){
            return new Result(SUCCESS, "修改成功");
        }
        return new Result(FAIL, "修改失败");
    }

    @ApiOperation("分页查询合同列表")
    @PostMapping("list")
    public Result findPage(
            @ApiParam("当前页码") @RequestParam(value = "now", required = false, defaultValue = "1") Integer now,
            @ApiParam("每页数量") @RequestParam(value = "size", required = false, defaultValue = "10") Integer size,
            @ApiParam("查询条件") @RequestBody(required = false) TContractQueryVO contractQueryVO
    ) {
        Page<TContract> page = new Page<>(now, size);
        LambdaQueryWrapper<TContract> wrapper = new LambdaQueryWrapper<>();

        // 构建查询条件
        if (contractQueryVO != null) {
            if (StringUtils.hasLength(contractQueryVO.getName())) {
                wrapper.like(TContract::getName, contractQueryVO.getName());
            }
            if (StringUtils.hasLength(contractQueryVO.getType())) {
                wrapper.eq(TContract::getType, contractQueryVO.getType());
            }
            if (StringUtils.hasLength(contractQueryVO.getPartyA())) {
                wrapper.like(TContract::getPartyA, contractQueryVO.getPartyA());
            }
            if (StringUtils.hasLength(contractQueryVO.getPartyB())) {
                wrapper.like(TContract::getPartyB, contractQueryVO.getPartyB());
            }
            if (StringUtils.hasLength(contractQueryVO.getPayWay())) {
                wrapper.eq(TContract::getPayWay, contractQueryVO.getPayWay());
            }
            if (StringUtils.hasLength(contractQueryVO.getPayType())) {
                wrapper.eq(TContract::getPayType, contractQueryVO.getPayType());
            }
            if (contractQueryVO.getStatus() != null) {
                wrapper.eq(TContract::getStatus, contractQueryVO.getStatus());
            }
            if (contractQueryVO.getMinAmount() != null) {
                wrapper.ge(TContract::getAmount, contractQueryVO.getMinAmount());
            }
            if (contractQueryVO.getMaxAmount() != null) {
                wrapper.le(TContract::getAmount, contractQueryVO.getMaxAmount());
            }
            if (contractQueryVO.getEffectiveTimeStart() != null) {
                wrapper.ge(TContract::getEffectiveTime, contractQueryVO.getEffectiveTimeStart());
            }
            if (contractQueryVO.getEffectiveTimeEnd() != null) {
                wrapper.le(TContract::getEffectiveTime, contractQueryVO.getEffectiveTimeEnd());
            }
            if (contractQueryVO.getTerminationTimeStart() != null) {
                wrapper.ge(TContract::getTerminationTime, contractQueryVO.getTerminationTimeStart());
            }
            if (contractQueryVO.getTerminationTimeEnd() != null) {
                wrapper.le(TContract::getTerminationTime, contractQueryVO.getTerminationTimeEnd());
            }
        }

        // 按创建时间倒序排列
        wrapper.orderByDesc(TContract::getId);


        Page<TContract> contractPage = tContractService.page(page, wrapper);
        return new Result(SUCCESS, "查询成功", contractPage);
    }


//        public TContractController(TContractService tContractService) {
//            this.tContractService = tContractService;
//        }

        @ApiOperation("下载合同设置模板")
        @GetMapping("/download")
        public void download(HttpServletResponse response) {
            // 1. 找到模板文件
            File file = null;
            try {
                file = ResourceUtils.getFile("classpath:templates/contract_template.xlsx");
            } catch (FileNotFoundException e) {
                log.warn("合同模板文件不存在！");
                return;
            }

            // 2. 响应
            if (file != null && file.isFile()) {
                String filename = file.getName();

                // 设置响应
                response.reset();
                response.setContentType("application/force-download");
                response.setCharacterEncoding("utf-8");
                response.setContentLength((int) file.length());
                response.setHeader("Content-Disposition", "attachment;filename=" + filename);

                // 边读边写
                try (
                        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
                ) {
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while ((len = bis.read(buffer)) != -1) {
                        bos.write(buffer, 0, len);
                        bos.flush();
                    }
                } catch (IOException e) {
                    log.error("合同模板下载出错：{}", e.getMessage());
                }
            }
        }

        @PostMapping("/upload")
        @ApiOperation("批量导入合同")
        public Result upload(@RequestParam("file") MultipartFile file) {
            try {
                if (file.isEmpty()) {
                    return new Result(FAIL, "请选择要上传的文件");
                }

                // 验证文件类型
                String originalFilename = file.getOriginalFilename();
                if (originalFilename == null ||
                        (!originalFilename.endsWith(".xls") && !originalFilename.endsWith(".xlsx"))) {
                    return new Result(FAIL, "请上传Excel文件(.xls或.xlsx格式)");
                }

                boolean success = tContractService.upload(file);
                if (success) {
                    return new Result(SUCCESS, "合同导入成功");
                } else {
                    return new Result(FAIL, "合同导入失败");
                }
            } catch (Exception e) {
                log.error("合同导入失败", e);
                return new Result(FAIL, "合同导入失败：" + e.getMessage());
            }
        }

        @GetMapping("/template")
        @ApiOperation("下载合同导入模板")
        public void downloadTemplate(HttpServletResponse response) {
            try {
                tContractService.downloadTemplate(response);
            } catch (Exception e) {
                log.error("合同模板下载失败", e);
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                try {
                    response.getWriter().write("{\"message\":\"合同模板下载失败：" + e.getMessage() + "\"}");
                } catch (IOException ex) {
                    log.error("写入错误响应失败", ex);
                }
            }
        }

    @ApiOperation("合同正文转PDF预览")
    @GetMapping("/pdf/{id}")
    public void previewPdf(@PathVariable("id") Integer id, HttpServletResponse response) throws Exception {
        tContractService.generatePdf(id, response);
    }

}